package thread;

/**
 * @author weim
 * @date 18-8-29
 */
public class MyWait {

    private static Object object = new Object();

    private static Integer index = 1;

    public static void main(String[] args) {

        for(int i=0; i<100; i++) {

            new Thread(() -> {

                sub("subOne");

            }).start();

            new Thread(() -> {

                sub("subTwo");

            }).start();

            new Thread(() -> {

                sub("subThree");

            }).start();

            new Thread(() -> {

                count("countOne");

            }).start();

            new Thread(() -> {

                count("countTwo");

            }).start();

        }

    }

    private static void count(String name) {

        synchronized (object) {

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            if(index > 10) {
                try {
                    object.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            index ++;
            System.out.println(name + " count>  " + index);

            object.notifyAll();

        }

    }

    private static void sub(String name) {

        synchronized (object) {

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            if(index <= 0) {
                try {
                    object.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            index--;
            System.out.println(name + " sub>  " + index);

            object.notifyAll();
        }

    }

}

